layui.use(['form','jquery','tree'], function () {
    var $ = layui.jquery;
    var form = layui.form;
    var tree = layui.tree;

    var formatdata=[];

    var data=[];
    data = getPlaceData();
    for(var i in data){     // pId为0时表示为根节点
        if(data[i].pid=='0'){
            var tempObject={};
            tempObject.title=data[i].text;
            tempObject.id=data[i].id;
            tempObject.children=getChildren(tempObject.id);
            formatdata.push(tempObject);
        }
    }
    function getChildren(id){    //递归体  即对每条data逐条递归找children
        var tempArray=[];
        for(var i in data){
            if(data[i].pid==id){
                var tempChild={};
                tempChild.title=data[i].text;
                tempChild.id=data[i].id;
                if(selectChildren(data[i].id)){   //若存在子节点，继续递归；否则为叶节点，停止递归
                    tempChild.children=getChildren(data[i].id);
                }
                tempArray.push(tempChild);
            }
        }
        return tempArray;
    }
    function selectChildren(id){   // 是否存在子节点
        for(var i in data){
            if(data[i].pid==id){
                return true;
            }
        }
        return false;
    }
    var index = tree.render({
        elem: '#userTree',  //绑定元素
        showCheckbox: false,
        data: formatdata,
        click: function(obj){
            //通过地址id获取地址全称
            var placeId = obj.data.id;
            $.ajax({
                type: "post",
                url: "/place/getPlaceNameById",
                data:{
                    "placeId" : placeId,
                },
                success: function (res){
                    console.log(res);
                    //关闭树,先获取父页面的id
                    var addressOpen = parent.layer.getFrameIndex(window.name);
                    if (res.state = true){
                        if (res.data.type == 3){
                            $("#address1",parent.document).val(res.data.place);
                            parent.layer.close(addressOpen);
                        }else {
                            layer.msg('请选择正确的地点',{time: 1000},function (){
                            });
                        }
                    }
                }
            })
        }
    });

    //获取树形组件数据
    function getPlaceData(){
        var placeData;
        $.ajax({
            type: "get",
            async: false,    //关闭，函数才能返回数据
            url: "/place/getPlaceForTree",
            dataType: "json",
            success: function (res){
                if (res.state == true){
                    placeData = res.data;
                }else {
                    layer.msg("查询出问题了");
                }
            }
        })
        return placeData;
    }
});